package com.laycoding.consumer.handler;

import com.laycoding.common.util.LoadBlance;
import com.laycoding.common.util.ZkUtils;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ZkConsumerHandler {

    private ConcurrentHashMap<String, Object> serviceMap = new ConcurrentHashMap<>();

    public String getUrl(CuratorFramework curatorFramework, String path, String name) {
        try {
            List<String> strings = ZkUtils.listService(curatorFramework, path, name);
          //  String[] split = path.split("/");
            for (String string : strings) {
                serviceMap.put(string, name);
            }
            return LoadBlance.getLoadBlance(strings);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public void doListener(CuratorFramework curatorFramework, String path) throws Exception {
        PathChildrenCache cache = new PathChildrenCache(curatorFramework, path, true);
        cache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);
        cache.rebuild();
        // Normal / BUILD_INITIAL_CACHE /POST_INITIALIZED_EVENT
        cache.getListenable().addListener((curatorFramework1, pathChildrenCacheEvent) -> {
            switch (pathChildrenCacheEvent.getType()) {
                case CHILD_ADDED:
                    ChildData data1 = pathChildrenCacheEvent.getData();
                    String path11 = data1.getPath();
                    String[] split1 = path11.split("/");
                    serviceMap.put(split1[2], data1.getData());
                    System.out.println("增加子节点");
                    break;
                case CHILD_REMOVED:
                    ChildData data = pathChildrenCacheEvent.getData();
                    String path1 = data.getPath();
                    String[] split = path1.split("/");
                    serviceMap.remove(split[2]);
                    System.out.println("删除子节点");
                    break;
                case CHILD_UPDATED:
                    System.out.println("更新子节点");
                    break;
                default:
                    break;
            }
        });
    }

}
